package com.softeem.xyblogmaster.interceptor;

import cn.hutool.core.util.StrUtil;
import com.softeem.xyblogmaster.exception.ServiceException;
import com.softeem.xyblogmaster.jwt.JwtUtil;
import com.softeem.xyblogmaster.util.AjaxResult;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.security.SignatureException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.softeem.xyblogmaster.util.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;

@Component
public class AuthInterceptor implements HandlerInterceptor {




    @Autowired
    private JwtUtil jwtUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{

                String token = request.getHeader("Authorization");
                if (StrUtil.isNotEmpty(token)) {
                    if (token.startsWith("Bearer")) {
                        token = token.replaceAll("Bearer ", "");
                        jwtUtil.verify(token);  //判断token签名是否失败
                        jwtUtil.isTokenExpired(token);  //判断token是否过期
                        ThreadContext.setItem(token);
                        return true;
                    }
                    else {
                        throw new ServiceException("401-token无效或者token被篡改");
                    }

                } else {
                    throw new ServiceException("401-没有携带token");

                }

        }catch (ServiceException e) {

            String message = e.getMessage();
            if(message.contains("-")){
                String[] split = message.split("-");
                int code=Integer.parseInt(split[0]);
                String msg=split[1];
                new AjaxResult(code,msg,null).print(response);

            }
            else{
                new AjaxResult(500,message,null).print(response);
            }
            // 返回错误信息
            return false; // 中断请求
        } catch (SignatureException e){
            new AjaxResult(401,"无效的token或者token已被篡改",null).print(response);

            return false;
        }
        catch (ExpiredJwtException e){
            new AjaxResult(401,"token已过期",null).print(response);
            return false;
        }
    }

}